//
//  NSOperationManager.m
//  仿写SDWebImage
//
//  Created by 倪啸天 on 16/10/15.
//  Copyright © 2016年 itheima. All rights reserved.
//

#import "NSOperationManager.h"
#import "HMDownloadIMGOperation.h"
#import "CZAdditions.h"

static id _instance;

@interface NSOperationManager ()

@property(nonatomic,strong) NSMutableDictionary *operationCache;
@property (nonatomic , strong) NSOperationQueue *queue ;

@property (nonatomic , strong)NSMutableDictionary *imgCache ;

@end


@implementation NSOperationManager

- (NSMutableDictionary *)imgCache {

    if (!_imgCache) {
        _imgCache = [NSMutableDictionary dictionary];
        
    }
    return _imgCache;
}

+ (instancetype)shareManager {

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc]init];
    });
    return  _instance;
}

- (NSOperationQueue *)queue {
    if (!_queue) {
        _queue = [NSOperationQueue new];
    }
    return _queue;
}

-(NSMutableDictionary *)operationCache{
    if(!_operationCache){
        _operationCache = [NSMutableDictionary dictionary];
    }
    return _operationCache;
}

//提供图片功能
- (void)downloadIMGWithUrlString:(NSString *)urlString andCompletedBlock:(void(^)(UIImage *image))completeBlock{
    
    UIImage *memImg = self.imgCache[urlString];
    if (memImg) {
        completeBlock(memImg);
        return;
    }
    else {
    
        UIImage *sandBoxImg = [UIImage imageWithContentsOfFile:[self getPathWithUrlString:urlString]];
        
        if (sandBoxImg) {
            
            [_imgCache setObject:sandBoxImg forKey:urlString];
            completeBlock(sandBoxImg);
            return;
        }
    }
    
    
    
    HMDownloadIMGOperation *op = [HMDownloadIMGOperation operationWithURLString:urlString complete:^(UIImage *image) {
        
        completeBlock(image);
        
        [self.imgCache setObject:image forKey:urlString];
    }];
    
    [self.operationCache setObject:op forKey:urlString];
    [self.queue addOperation: op];



}

//取消
- (void)cancelOperationWithUrlString:(NSString *)urlString {
    
        HMDownloadIMGOperation *preOP = self.operationCache[urlString];
        if (preOP) {
            
            [preOP cancel];
        }

}

- (NSString *) getPathWithUrlString:(NSString *)urlString {
    
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    
    NSString *fileName = [urlString cz_md5String];
    
    return [cachePath stringByAppendingPathComponent:fileName];
}


@end
